#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import json

from common.util.exec_utils import su_exec_rm_cmd
from redis import log
from common.common import output_result_file, output_execution_result_ex
from common.const import ParamConstant, SubJobStatusEnum
from common.common_models import SubJobDetails


class JobProgress:
    @staticmethod
    def get_progress(pid, job_id, sub_job_id, progress_type):
        # 从cache仓获取进度信息，写入结果文件中
        progress = JobProgress.open_progress_from_cache(job_id, sub_job_id, progress_type)
        output_result_file(pid, progress)

    @staticmethod
    def write_progress_to_cache(job_id, sub_job_id, content, progress_type):
        file_path = os.path.join(ParamConstant.RESULT_PATH, progress_type + '_' + job_id + '_' + sub_job_id)
        su_exec_rm_cmd(file_path, check_white_black_list_flag=False)
        log.info(f'write progress to file: {file_path}')
        output_execution_result_ex(file_path, content)

    @staticmethod
    def open_progress_from_cache(job_id, sub_job_id, progress_type):
        file_path = os.path.join(ParamConstant.RESULT_PATH, progress_type + '_' + job_id + '_' + sub_job_id)
        log.info(f'read progress from cache: {file_path}')
        try:
            with open(file_path, "r", encoding='UTF-8') as file:
                json_dict = json.loads(file.read())
            if int(json_dict.get("progress", 0)) == 100:
                su_exec_rm_cmd(file_path, check_white_black_list_flag=False)
            return json_dict
        except Exception as err:
            log.info(err, exec_info=True)
            progress_content = SubJobDetails(
                taskId=job_id, subTaskId=sub_job_id, taskStatus=SubJobStatusEnum.FAILED.value, progress=100).dict(
                by_alias=True)
            return progress_content
